<?php

class Logon extends CI_Controller {

	public function index()
	{
		//Determine if the user is loged in.
		if ($this->session->userdata('user_logedin')) {
			//If the user is loged in then redirect to start page.
			redirect('start');
		}
		else {
			//Loading libraries for form handling.
			$this->load->helper('form');
			$this->load->library('form_validation');
			
			//Loading basic templates.
			$this->load->view('templates/v_header');
			$this->load->view('templates/v_menu_basic');
			
			//Setting the delimiters for error messages so they can be styled by CSS.
			$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
			
			//Setting the form validation rules.
			$this->form_validation->set_rules('username', 'username', 'required');
			$this->form_validation->set_rules('password', 'password', 'required');
			
			//Resetting login error message.
			$page_data['login_error'] = '';
			
			//Validating data input.
			if ($this->form_validation->run())
			{
				//Creating an user object.
				$this->load->model('m_user', 'user');
				
				//Getting the entered password and username.
				$password = $this->input->post('password');
				$username = $this->input->post('username');
				
				//Trying to login user.
				$result = $this->user->login($username, $password);
				
				if ($result == 0) {
					redirect('start'); //If loged in, redirect to start page.
				}
				elseif ($result == 1) {
					//Setting error messages for inactivated account
					$page_data['login_error'] = '<p class="error">Your account is not activated. Go to ' . anchor('resend/activation', 'Resend activation link') . ' if you have not got your activation link.</p>';
				}
				else {
					//Setting error messages for incorrect user information.
					$page_data['login_error'] = '<p class="error">Incorrect username or password.</p>';
				}
			}
			
			//Repopulating the form.
			$page_data['entered_username'] = set_value('username');
			
			//Create links for forgotten password/username
			$page_data['forgotten_username_link'] = anchor('resend/username', 'Forgot username');
			$page_data['forgotten_password_link'] = anchor('resend/password', 'Forgot password');
			
			//If not valid, load login page.
			$this->load->view('pages/v_logon', $page_data);
			
			//Loading footer.
			$this->load->view('templates/v_footer');
		}
	}
}
?>